﻿using Dm.util;
using LPLS.CollectionHardProtocol.OPCUAModules.OPCUABAseModule;
using LPLS.RuleEngineBaseCommon.CollectionVarRuleEngineModule;
using Masuit.Tools.Logging;
using Opc.Ua;
using Opc.Ua.Client;
using Opc.Ua.Server;
using OPCUA.Common;

namespace LPLS.CollectionHardProtocol.OPCUAModules.OPCUARuleJudgeModule
{
    public  class OPCUARuleJudgeDTO : OPCUABaseDTO
    {

        public OPCUARuleJudgeDTO(string url ) 
        {

            Url= url;
            OPCUAClient = new MyOPUAHelper(Url);

        }
        public override void BatchRead()
        {
          
            Dictionary<string, object> data = new Dictionary<string, object>();
            List<NodeId> li = new List<NodeId>();
            foreach (var item in Nodes)
            {
                li.Add(item);
            }
            var opcuadata = this.OPCUAClient.GetBatchNodeDatasOfSync(li);
            if (opcuadata == null || opcuadata.Count == 0)
            {
                return;
            }
            foreach (var item in opcuadata)
            {
                var opkey = item.Key;//地址
                var opvalue = item.Value.Value;//值
                var oprule = PLCVarList.Where(e => e.VarAddress == opkey)?.FirstOrDefault()?.VarName;
                if (oprule == null) { return; }
                data.Add(oprule, opvalue);
            }
            CollectionVarRuleEngineConfig ruleengine = new CollectionVarRuleEngineConfig(
                JsonName, DeviceID, CompentID, PLCVarList
                );
            ruleengine.DealData(data);
        }

      

        public override void SubCallBackContinue(string key, Opc.Ua.Client.MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs args)
        {
            var tagname = monitoredItem.StartNodeId.ToString();
            if (key != GroupName)
            {
                LogManager.Info($"分组不正确该 该组未分配该标签 OPCUA名称：{OPCUAName} OPCUA连接：{OPCUAClient.URl} 标签名称：{tagname}");
                return;
            }
            Dictionary<string, object> data = new Dictionary<string, object>();
            List<NodeId> li = new List<NodeId>();
            foreach (var item in Nodes)
            {
                li.Add(item);
            }
            var opcuadata = this.OPCUAClient.GetBatchNodeDatasOfSync(li);
            if (opcuadata == null || opcuadata.Count == 0)
            {
                return;
            }
            foreach (var item in opcuadata)
            {
                var opkey = item.Key;//地址
                var opvalue = item.Value;//值
                var oprule = PLCVarList.Where(e => e.VarAddress == opkey)?.FirstOrDefault()?.VarName;
                if (oprule == null) { return; }
                data.Add(oprule, opvalue);
            }
            CollectionVarRuleEngineConfig ruleengine = new CollectionVarRuleEngineConfig(
                JsonName, DeviceID, CompentID, PLCVarList
                );
            ruleengine.DealData(data);
        }
    }
}
